#include<iostream>
#include<unistd.h>
#include<cerrno>
#include<cstring>
#include<cassert>

int main()
{
    //创建管道
    int pipefd[2];
    int n = pipe(pipefd);
    if(n == -1)
    {
        std::cout << "pipe error, " << errno << ": " << strerror(errno) << std::endl;
        return 1;
    }
    //创建子进程
    pid_t id = fork();
    assert(id != -1);
    if(id == 0)
    {
        //子进程读
        close(pipefd[1]);
        char buffer[1024];
        while(true)
        {
            int n = read(pipefd[0],buffer,sizeof(buffer)-1);
            if(n>0)
            {
                buffer[strlen(buffer)] = '\0';
                std::cout<<buffer<<std::endl;
            }
            else if(n==0)
            {
                std::cout<<"我已读到文件的结尾"<<std::endl;
                break;
            }
            else
            {
                std::cout<<"读取异常"<<std::endl;
                break;
            }
        }
        close(pipefd[0]);
        exit(0);
    }

    //父进程写
    close(pipefd[0]);
    char* b = "i am father";
    write(pipefd[1],b,strlen(b));
    close(pipefd[1]);
    return 0;
}